#include "stm32f10x.h"                  // Device header

/*
输入捕获初始化
*/
void IC_Init(void)
{
	// Open RCC_Clock
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	TIM_InternalClockConfig(TIM3);
	
	// GPIO_PA_6_Input_Init
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;				// 作为TIM3_CH1的输入引脚,选择上拉输入
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;					// PA_6 Input,为什么是PA_6, !!!查表!!!
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	// TimerBase_Init
	TIM_TimeBaseInitTypeDef TimerInitStruture;
	TimerInitStruture.TIM_ClockDivision = TIM_CKD_DIV1;
	TimerInitStruture.TIM_CounterMode = TIM_CounterMode_Up;
	TimerInitStruture.TIM_Period = 65536 - 1;                     // ARR给最大, 防止溢出, if被测频率太低
	TimerInitStruture.TIM_Prescaler = 72 - 1;					  // PSC, 决定Fc的值     ?????
	TimerInitStruture.TIM_RepetitionCounter = 0;
	TIM_TimeBaseInit(TIM3, &TimerInitStruture);
	
	// Input_Capture_Init
	TIM_ICInitTypeDef TIM3_ICInitStructure;
//	TIM_ICStructInit(&TIM3_ICInitStructure);
	TIM3_ICInitStructure.TIM_Channel = TIM_Channel_1;			// TIM3_CH1 对应的引脚就是PA_6
	TIM3_ICInitStructure.TIM_ICFilter = 0xF;					// No_Filter
	TIM3_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;// 上升沿
	TIM3_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;		// ?????
	TIM3_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;		// 交叉还是不交叉
	
	TIM_PWMIConfig(TIM3, &TIM3_ICInitStructure);				// 配置PWMI模式, 自动配置
//	TIM_ICInit(TIM3, &TIM3_ICInitStructure);
	
	// 主从触发
	TIM_SelectInputTrigger(TIM3, TIM_TS_TI1FP1);				// 选择(TIM3输入触发源)主模式
	TIM_SelectSlaveMode(TIM3, TIM_SlaveMode_Reset);				// 选择从模式
	
	
	// Start TIM3
	TIM_Cmd(TIM3, ENABLE);
}


/*
输出捕获的频率
*/

uint16_t IC_GetFreq(void)
{
	return (71000000 / TIM_GetPrescaler(TIM3)) / (TIM_GetCapture1(TIM3) + 1);			// 注意是TIM3_CH1, 所以是...Capture1
//	return 1000000 / (TIM_GetCapture1(TIM3) + 1);
}


/*
查看捕获的占空比
*/
uint16_t IC_GetDuty(void)
{
	return (TIM_GetCapture2(TIM3) + 1) * 100 / (TIM_GetCapture1(TIM3) + 1);
}


/*
查看IC的预分频值
*/

uint16_t IC_GetPsc(void)
{
	return TIM_GetPrescaler(TIM3);
}
